package com.blockchain.securewallet.utils;

import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class StringUtil {

    /**
     * 过滤特殊字符
     */
    public static String removeInvalidChar(String str) {
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;＇,\\[\\].<>/?～！＠＃￥％……＆＊（）——＋｜｛｝【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("")
                .trim();
    }

    /**
     * 生成size位随机数
     */
    public static String createRandomKey(int size) {
        char[] c = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
        Random random = new Random(); // 初始化随机数产生器
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; i++) {
            sb.append(c[Math.abs(random.nextInt()) % c.length]);
        }
        return sb.toString();
    }

    /**
     * 过滤空白符
     */
    public static String replaceEmptyChar(@NonNull String sourceStr, String replaceStr) {
        return StringUtil.replaceInvalidChar(sourceStr, "\\s*", replaceStr);
    }

    /**
     * 过滤字符（正则）
     */
    public static String replaceInvalidChar(@NonNull String sourceStr, @NonNull String pattern, String replaceStr) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(sourceStr);
        return m.replaceAll(replaceStr).trim();
    }

    public static long getFolderSize(java.io.File file) throws Exception {
        long size = 0;
        java.io.File[] fileList = file.listFiles();
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isDirectory()) {
                size = size + getFolderSize(fileList[i]);
            } else {
                size = size + fileList[i].length();
            }
        }
        return size / 1024;
    }

    /**
     * 移除字符串中的空格
     */
    public static String removeEmptyCharString(String source) {
        String formatString = source.trim();
        formatString = formatString.replaceFirst(" ", "");
        return formatString;
    }

    /**
     * 获取textview的高度
     */
    public static int getTextviewHeight(Context context, CharSequence text, int textSize, int deviceWidth, int padding) {
        TextView textView = new TextView(context);
        textView.setPadding(padding, 0, padding, padding);
        textView.setText(text, TextView.BufferType.SPANNABLE);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(
                deviceWidth,
                View.MeasureSpec.AT_MOST
        );
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        textView.measure(widthMeasureSpec, heightMeasureSpec);
        return textView.getMeasuredHeight();
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    public static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim()
                .toLowerCase();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }

        return strAllParam;
    }

    /**
     * 查找网址
     */
    public static ArrayList<String> findUrl(String text) {
        ArrayList<String> urls = new ArrayList<String>();
        Pattern p;
        p = Pattern.compile(
                "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
        // p =
        // Pattern.compile("(http|www|ftp|)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)(/(\\w+(-\\w+)*))*(\\.?(\\w)*)(\\?)?(((\\w*%)*
        // (\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*)*
        // (\\w*)*)$");
        Matcher m;
        m = p.matcher(text);// 获得匹配
        String res = "";

        while (m.find()) {
            String url = m.group();
            urls.add(url);
            Log.i("findUrl", url);
        }
        return urls;
    }

    /**
     * 是否拥有非法字符
     */
    public static boolean hasIlleglalString(String content) {
        if (content.contains("@") || content.contains("#") || content.contains(" ") || content.contains(
                "/") || content.contains("*") || content.contains("-")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isLetter(String source) {
        Pattern pattern = Pattern.compile("[a-zA-Z]");
        Matcher matcher = pattern.matcher(source);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isNumber(String source) {
        Pattern pattern = Pattern.compile("[0-9]");
        Matcher matcher = pattern.matcher(source);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 关键字高亮 （不支持模糊搜索）
     *
     * @param keyWord      关键字
     * @param color        高亮颜色
     * @param sourceString 完整的源文本
     * @return 拼接后的文字（CharSequence）
     */
    public static SpannableStringBuilder highLightKeyWord(String keyWord, int color,
                                                          String sourceString) {
        SpannableStringBuilder spanBuilder = null;
        if (!TextUtils.isEmpty(sourceString) && !TextUtils.isEmpty(keyWord)
                && sourceString.contains(keyWord)) {
            spanBuilder = new SpannableStringBuilder(
                    sourceString);
            int index = sourceString.indexOf(keyWord);
            if (index >= 0) {
                int sourceStrLen = sourceString.length();
                // 遍历关键字，当关键字没有的时候,跳出循环
                while (index < sourceStrLen && index >= 0) {
                    spanBuilder.setSpan(new ForegroundColorSpan(color), index,
                            index + keyWord.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    );
                    spanBuilder.setSpan(new StyleSpan(Typeface.NORMAL), index,
                            index + keyWord.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    );
                    index = sourceString.indexOf(
                            keyWord,
                            index + keyWord.length()
                    );
                }
            }
        } else {
            if (TextUtils.isEmpty(sourceString)) {
                spanBuilder = new SpannableStringBuilder("");
            } else {
                spanBuilder = new SpannableStringBuilder(sourceString);
            }
        }

        return spanBuilder;
    }

    /**
     * 关键字高亮，其他字规定颜色 (因为spannablestringbuilder会以黑色默认)【不支持模糊搜索】
     *
     * @param defaultColor 其他字的颜色
     */
    public static SpannableStringBuilder highLightKeyWord(String keyWord, int defaultColor, int color,
                                                          String sourceString) {
        SpannableStringBuilder spanBuilder = null;
        if (!TextUtils.isEmpty(sourceString) && !TextUtils.isEmpty(keyWord)
                && sourceString.contains(keyWord)) {
            spanBuilder = new SpannableStringBuilder(sourceString);
            spanBuilder.setSpan(
                    new ForegroundColorSpan(defaultColor),
                    0,
                    sourceString.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
            int index = sourceString.indexOf(keyWord);
            if (index >= 0) {
                int sourceStrLen = sourceString.length();
                // 遍历关键字，当关键字没有的时候,跳出循环
                while (index < sourceStrLen && index >= 0) {
                    spanBuilder.setSpan(
                            new ForegroundColorSpan(color),
                            index,
                            index + keyWord.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    );
                    spanBuilder.setSpan(
                            new StyleSpan(Typeface.NORMAL),
                            index,
                            index + keyWord.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    );
                    index = sourceString.indexOf(keyWord, index + keyWord.length());
                }
            }
        } else {
            if (TextUtils.isEmpty(sourceString)) {
                spanBuilder = new SpannableStringBuilder("");
            } else {
                spanBuilder = new SpannableStringBuilder(sourceString);
                spanBuilder.setSpan(
                        new ForegroundColorSpan(defaultColor),
                        0,
                        sourceString.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
            }
        }
        return spanBuilder;
    }

    /**
     * 从资源文件拿到文字
     */
    public static String getResourceString(int strId) {
        String result = "";
        try {
            result = WalletApp.getInstance()
                    .getResources()
                    .getString(strId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 从资源文件得到文字并format
     */
    public static String getResourceStringAndFormat(int strId, Object... objs) {
        String result = "";
        if (strId > 0) {
            result = String.format(Locale.getDefault(), WalletApp.getInstance().getResources().getString(strId), objs);
        }
        return result;
    }

    /**
     * 直接文字进行format
     */
    public static String getResourceStringAndFormat(String str, Object... objs) {
        String result = "";
        if (StringUtil.noEmpty(str)) {
            result = String.format(Locale.getDefault(), str, objs);
        }
        return result;
    }

    /**
     * 半角转为全角  解决排版不整齐
     */
    public static String toDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375) {
                c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    public static String format(String source, Object... keys) {
        if (TextUtils.isEmpty(source)) return "";
        String result = String.format(Locale.getDefault(), source, keys);
        return result;
    }

    public static boolean noEmpty(String str) {
        return !TextUtils.isEmpty(str);
    }

    //判断是否为空
    public static boolean isEmpty(String str) {
        return TextUtils.isEmpty(str);
    }

    /**
     * 解压gzip的内容
     */
    public static String uncompressGzipToString(byte[] b) {
        if (b == null || b.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(b);

        try {
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toString();
    }

    public static String formatExceptionTips(int errorCode) {
        return String.format(WalletApp.getInstance().getResources().getString(R.string.app_exception), String.valueOf(errorCode));
    }

    public static boolean checkNoEmptyStrs(String... strings) {
        boolean noEmpty = true;
        for (int i = 0; i < strings.length; i++) {
            if (TextUtils.isEmpty(strings[i])) {
                noEmpty = false;
                break;
            }
        }
        return noEmpty;
    }

    public static boolean checkEquals(String origin, String... values) {
        for (String value : values) {
            if (TextUtils.equals(origin, value)) {
                return true;
            }
        }
        return false;
    }
}
